<?php
/**
 * Created by PhpStorm.
 * User: 64423
 * Date: 2018/10/16
 * Time: 11:59
 */

namespace app\shop\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\shop\model\ArticleCategoryModel;

class ArticleCategory extends Admin
{
    public function index()
    {
        $list = ArticleCategoryModel::getAllList();
        $page = $list->render();
        return ZBuilder::make('table')
            ->setPageTitle('文章分类列表')
            ->setTableName('article_category')
            ->addColumns([
                ['id', 'ID'],
                ['name', '分类名称'],
                ['img', '缩略图', 'picture'],
                ['sort', '排序', 'text.edit'],
                ['right_button', '操作']
            ])
            ->addTopButton('add')
            ->addRightButtons('edit,delete')
            ->setRowList($list)
            ->setPages($page)
            ->fetch();
    }

    public function add()
    {
        if(request()->isPost()){
            $this->store();
        }
        return ZBuilder::make('form')
            ->setPageTitle('添加文章分类')
            ->setUrl(url('add'))
            ->addText('name','分类名称')
            ->addText('sort','排序','','100')
            ->addImage('img','缩略图')
            ->fetch();
    }

    public function edit($id=0)
    {
        if(request()->isPost()){
            $this->store();
        }
        $data = ArticleCategoryModel::getOne($id);
        return ZBuilder::make('form')
            ->setPageTitle('编辑文章分类')
            ->setUrl(url('edit'))
            ->addHidden('id')
            ->addText('name','分类名称')
            ->addText('sort','排序')
            ->addImage('img','缩略图')
            ->setFormData($data)
            ->fetch();
    }

    private function store()
    {
        $id= input('param.id',0);
        $data = input('post.');
        $validate = new \app\shop\validate\ArticleCategory();
        if(!$validate->check($data)){
            $this->error($validate->getError());
        }
        $this->nameExist($data['name'], $id);
        $res = ArticleCategoryModel::store($data,$id);
        if($res){
            $this->success('保存成功',url('index'));
        }else{
            $this->error('保存失败');
        }
    }

    private function nameExist($name, $id)
    {
        if(ArticleCategoryModel::nameExist($name, $id)){
            $this->error('名称已存在');
        }
    }
}